//
//  ZHEngine.swift
//  onemeetingmac
//
//  Created by 张衡 on 2020/3/13.
//  Copyright © 2020 onemeeting. All rights reserved.
//

import Foundation

open class ZHEngine: NSObject {
    static let shared = ZHEngine()
    
    lazy var window: WKWindow = {
        let window = WKWindow()
        return window
    }()
    
    lazy var windowController: NSWindowController = {
        let windowController = NSWindowController()
        return windowController
    }()
    
    class func orderFront(inWindow:NSWindow, viewController:NSViewController,sender: Any?) {
        let window = WKWindow()
        var winFrame = NSRect.zero
        if (window.inLiveResize)  {
            winFrame.origin.x -= ((window.frame.size.width) - winFrame.size.width)/2
            winFrame.size.width += ((window.frame.size.width) - winFrame.size.width)
            winFrame.origin.y = (window.frame.origin.y)
            winFrame.size.height = (window.frame.height)
            window.setFrame(winFrame, display: true)
        }
        inWindow.addChildWindow(window, ordered: NSWindow.OrderingMode.above)
        
        window.contentViewController = viewController
        let windowC = NSWindowController()
        windowC.window = window
        windowC.window?.orderFront(sender)
    }
    
}

extension NSWindow {
    func orderOrChildFront(_ sender: Any?,window:NSWindow?) {
        if Td.fullScreen {
            if let win = window {
                win.addShareChildWindow(self, ordered: NSWindow.OrderingMode.above)
            }
        }else {
            self.lorderFront(sender)
        }
    }
    func lorderFront(_ sender: Any?,makeKey:Bool=true) {
        var isVisible:Bool = false
        let windows = NSApplication.shared.windows
        windows.forEach { (win) in
            if let controller = win.contentViewController,let selfController = self.contentViewController {
                if controller.isKind(of: selfController.classForCoder) == true {
                    if win.isVisible == true {
                        isVisible = true
                        if makeKey {
                            win.makeKeyAndOrderFront(sender)
                        }else {
                            win.orderFront(sender)
                        }
                    }
                }
            }
            
        }
        if isVisible == false {
            if makeKey {
                self.makeKeyAndOrderFront(sender)
            }else {
                self.orderFront(sender)
            }
        }
    }
}

extension NSViewController {
    func orderFront(window:NSWindow,sender: Any?){
        window.contentViewController = self
        window.orderFront(sender)
    }
}
